<?php

// 文件上传控制器（主要是上传图片）
class UploadController
{
    private $projectBaseURL = "http://localhost/web-course-backend/";

    private function uuid()
    {
        $chars = md5(uniqid(mt_rand(), true));
        $uuid = substr($chars, 0, 8) . '-'
            . substr($chars, 8, 4) . '-'
            . substr($chars, 12, 4) . '-'
            . substr($chars, 16, 4) . '-'
            . substr($chars, 20, 12);
        return $uuid;
    }

    // POST
    public function image()
    {
        if ($_FILES["file"]["error"] > 0) {
            return ReturnHelper::failed([], "文件过大");
        }
        else {
            $array = $_FILES["file"]["type"];
            $array = explode("/", $array);
            $newfilename = $this->uuid();
            $fileFullName = $newfilename . "." . $array[1];
            $avatar_url = "upload/img/";
            $avatar_url = $avatar_url . $fileFullName;
            move_uploaded_file($_FILES["file"]["tmp_name"], $avatar_url);
            return ReturnHelper::success(["filePath"=>$this->projectBaseURL . $avatar_url], "图片已上传到上述路径");
        }
    }
}